//
//  XKCertificationController.m
//  XKJF
//
//  Created by xyg on 2016/12/17.
//  Copyright © 2016年 xiaokang100. All rights reserved.
//

#import "XKCertificationController.h"
#import "XKCertificationCell.h"
#import "IDAuthViewController.h"

@interface XKCertificationController ()
@property (nonatomic, strong) UIButton *confirmButton;

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, copy) NSString *nation;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSString *idnumber;
@property (nonatomic, copy) NSString *tradepassword;
@property (nonatomic, copy) NSString *tradepasswordconfirm;
@property (nonatomic, strong) NSMutableArray *textArrM;

@end

@implementation XKCertificationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _textArrM = [NSMutableArray array];
    
    self.navigationItem.title = @"实名认证";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.tableView registerClass:[XKCertificationCell class] forCellReuseIdentifier:@"XKCertificationCell"];
    
    
    // 提示语
    UILabel *label = [UILabel getLabWithText:@"请填写本人身份证信息!" textFont:Font_13 textColor:[UIColor redColor] textAlignment:NSTextAlignmentCenter];
    label.frame = CGRectMake(0, 0, Main_Width, 44);
    self.tableView.tableHeaderView = label;
    
    
    // 提交信心按钮
    UIButton *button = [UIButton getClickBtnWithTitle:@"提交实名认证信息"];
    button.enabled = YES;
    _confirmButton = button;
    [button addTarget:self action:@selector(confirmButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Width, 50*Scale_W)];
    button.frame = CGRectMake(20*Scale_W, 20*Scale_W, Main_Width-2*20*Scale_W, 44*Scale_W);
    [containerView addSubview:button];
    self.tableView.tableFooterView = containerView;
    
    
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithTitle:@"识别" style:UIBarButtonItemStylePlain target:self action:@selector(OCREvent:)];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OCRIDRecognitionResult:) name:@"IDNUMBERINFORMATION" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XKCertificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XKCertificationCell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.secureTextEntry = NO;
        cell.title = @[@"姓名:",@"性别:",@"民族:",@"住址:",@"身份证号:"][indexPath.row];
        cell.placeholder = @[@"请输入姓名",@"请输入性别",@"请输入民族",@"请输入身份证住址",@"请输入身份证号"][indexPath.row];
        cell.userInfoType = indexPath.row;
        if (_textArrM.count == 5) {
            cell.text = _textArrM[indexPath.row];
        }
    } else {
        cell.secureTextEntry = YES;
        cell.title = @[@"交易密码:",@"确认密码:"][indexPath.row];
        cell.placeholder = @[@"请输入6位数字交易密码",@"请确认交易密码"][indexPath.row];
        cell.userInfoType = indexPath.row + 5;
    }
    
    cell.TextChangedBlock = ^(NSString *text) {
        if (indexPath.section == 0) {
            switch (indexPath.row) {
                case 0: _name = text; break;
                case 1: _gender = text; break;
                case 2: _nation = text; break;
                case 3: _address = text; break;
                case 4: _idnumber = text; break;
            }
        } else if (indexPath.section == 1) {
            switch (indexPath.row) {
                case 0: _tradepassword = text; break;
                case 1: _tradepasswordconfirm = text; break;
            }
        }
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 20.0;
    } else {
        return 0.01;
    }
}




#pragma mark - 获取用户信息
- (void)loadUserCertificationState {
    [APIManager POSTRequestWith:APIPOSTRequestState_UserInformation parameters:@{} successBlock:^(NSDictionary *successDict) {
        NSLog(@"%@",[NSString jsonToString:successDict]);
        [UserDefaults setObjectWithData:successDict[@"data"]];
    } failureBlock:^(NSDictionary *failureDict) {
    } errorBlock:^(NSError *error) {
        
    }];
}



#pragma mark - confirmButtonEvent
- (void)confirmButtonEvent:(UIButton *)sender {
    NSLog(@"\n姓名:%@\n性别:%@\n民族:%@\n住址:%@\n身份证号:%@\n交易密码:%@\n确认密码:%@",_name,_gender,_nation,_address,_idnumber,_tradepassword,_tradepasswordconfirm);
    
    if (IsEmptyStr(_name)) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名"];
        return;
    }
    
    if (IsEmptyStr(_gender)) {
        [SVProgressHUD showInfoWithStatus:@"请输入性别"];
        return;
    }
    
    if (IsEmptyStr(_nation)) {
        [SVProgressHUD showInfoWithStatus:@"性输入民族"];
        return;
    }
    
    if (IsEmptyStr(_address)) {
        [SVProgressHUD showInfoWithStatus:@"请输入身份证住址"];
        return;
    }
    
    if (IsEmptyStr(_idnumber)) {
        [SVProgressHUD showInfoWithStatus:@"请输入身份证号"];
        return;
    }
    
    if (_tradepassword.length < 6) {
        [SVProgressHUD showInfoWithStatus:@"请输入6位数字交易密码"];
        return;
    }
    
    if (_tradepasswordconfirm.length < 6) {
        [SVProgressHUD showInfoWithStatus:@"请确认6位数字交易密码"];
        return;
    }
    
    if (![_tradepassword isEqualToString:_tradepasswordconfirm]) {
        [SVProgressHUD showInfoWithStatus:@"两次密码输入不一致"];
        return;
    }
    
    
    [SVProgressHUD show];
    
    NSString *phone = [UserDefaults objectWithKey:@"phone"];
    
    @weakify(self);
    [APIManager POSTRequestWith:APIPOSTRequestState_Verified parameters:@{@"mo":phone, @"name":_name, @"gender":_gender, @"nation":_nation, @"address":_address, @"pwdtrade":_tradepassword, @"idcard":_idnumber} successBlock:^(NSDictionary *successDict) {
        @strongify(self);
        [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
        [UserDefaults setObjectWithData:successDict[@"data"]];
        [self loadUserCertificationState];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        [MobClick event:@"UserRealnameAuthentication"]; // 友盟事件统计
    } failureBlock:^(NSDictionary *failureDict) {
        
    } errorBlock:^(NSError *error) {
        
    }];
    
}

#pragma mark - OCR识别
- (void)OCREvent:(UIBarButtonItem *)sender {
    IDAuthViewController *IDAuthVC = [[IDAuthViewController alloc] init];
//    [self.navigationController pushViewController:IDAuthVC animated:YES];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:IDAuthVC];
    [self presentViewController:nav animated:YES completion:nil];
}


#pragma mark - OCR识别确认结果
- (void)OCRIDRecognitionResult:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    
    [_textArrM addObject:userInfo[@"name"]];
    [_textArrM addObject:userInfo[@"gender"]];
    [_textArrM addObject:userInfo[@"nation"]];
    [_textArrM addObject:userInfo[@"address"]];
    [_textArrM addObject:userInfo[@"idNumner"]];
    
    _name = userInfo[@"name"];
    _gender = userInfo[@"gender"];
    _nation = userInfo[@"nation"];
    _address = userInfo[@"address"];
    _idnumber = userInfo[@"idNumner"];
    
    [self.tableView reloadData];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
